package com.logic.landseaserver.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.logic.common.exception.BusinessException;
import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.common.ws.dto.system.FileDTO;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.util.JsonObjectUtils;
import com.logic.landseaserver.domain.Activity;
import com.logic.landseaserver.domain.ActivityList;
import com.logic.landseaserver.domain.ActivityListDetail;
import com.logic.landseaserver.domain.ActivityListDetailDynamic;
import com.logic.landseaserver.domain.DynamicProjectInfo;
import com.logic.landseaserver.domain.Project;
import com.logic.landseaserver.persistence.read.ActivityListDetailDynamicReadMapper;
import com.logic.landseaserver.persistence.read.ActivityListDetailReadMapper;
import com.logic.landseaserver.persistence.read.ActivityListReadMapper;
import com.logic.landseaserver.persistence.read.ActivityReadMapper;
import com.logic.landseaserver.persistence.read.ProjectReadMapper;
import com.logic.landseaserver.persistence.write.ActivityListDetailDynamicWriteMapper;
import com.logic.landseaserver.persistence.write.ActivityListDetailWriteMapper;
import com.logic.landseaserver.persistence.write.ActivityListWriteMapper;
import com.logic.landseaserver.persistence.write.ActivityWriteMapper;
import com.logic.landseaserver.service.IActivityService;
import com.logic.landseaserver.ws.dto.ActivityAndActivityListDTO;
import com.logic.landseaserver.ws.dto.ActivityDTO;
import com.logic.landseaserver.ws.dto.ActivityListDTO;
import com.logic.landseaserver.ws.dto.ActivityListDTO1;
import com.logic.landseaserver.ws.dto.ActivityListDetailDTO;
import com.logic.landseaserver.ws.dto.ActivityListDetailDynamicDTO;
import com.logic.landseaserver.ws.dto.ActivityDynamicReq;
import com.logic.landseaserver.ws.dto.ProjectDTO1;
import com.logic.landseaserver.ws.dto.SaveActivityListDetailDynamicReq;
import com.logic.system.domain.SystemFile;
import com.logic.system.service.impl.FileService;
import com.logic.system.ws.dto.FileConverter;

/**
 * @Author: jack
 * @Date: 2017/5/4
 * @Description: 活动接口实现类
 */
@Service
public class ActivityServiceImpl implements IActivityService
{
    private static final Logger LOG = LoggerFactory.getLogger(ActivityServiceImpl.class);
    
    @Autowired
    private ActivityReadMapper activityReadMapper;
    
    @Autowired
    private ActivityWriteMapper activityWriteMapper;
    
    @Autowired
    private ActivityListWriteMapper activityListWriteMapper;
    
    @Autowired
    private ActivityListDetailWriteMapper activityListDetailWriteMapper;
    
    @Autowired
    private ActivityListDetailDynamicWriteMapper activityListDetailDynamicWriteMapper;
    
    @Autowired
    private ActivityListReadMapper activityListReadMapper;
    
    @Autowired
    private ActivityListDetailReadMapper activityListDetailReadMapper;
    
    @Autowired
    private ActivityListDetailDynamicReadMapper activityListDetailDynamicReadMapper;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private ProjectReadMapper projectReadMapper;
    
    @Override
    public void delete(String arg0)
        throws BusinessException
    {
        // TODO Auto-generated method stub
        
    }
    
    @Override
    public ActivityDTO get(Integer arg0)
        throws BusinessException
    {
        
        return activityReadMapper.getActivityDetail(arg0);
    }
    
    @Override
    public int insertActivity(ActivityDTO activityDTO)
        throws BusinessException
    {
        int activityInt = 0;// 唯一性验证
        if (validateForInsert(activityDTO))
        {// 需补充验证
            Activity activity = new Activity();
            int orderId;
            setActivityByActivityDTO(activity, activityDTO);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            activity.setCreatedBy(activityDTO.getUserId());
            activity.setCreatedDtm(date);
            activity.setLastModifiedBy(activityDTO.getUserId());
            activity.setLastModifiedDtm(date);
            // order.setOrderFromPage(orderFromPage);
            activityWriteMapper.insertSelective(activity);
            activityInt = activity.getId();
        }
        else
        {
            activityInt = 4010001;// 验证唯一性
        }
        return activityInt;
    }
    
    @Override
    public List<ActivityDTO> query(QueryUtil queryUtil)
    {
        List<ActivityDTO> result = activityReadMapper.getActivityDTOList(queryUtil);
        return result;
    }
    
    @Override
    public void update(Object obj)
        throws BusinessException
    {
        
    }
    
    @Override
    public Boolean validate(Object arg0)
        throws BusinessException
    {
        Boolean pass = true;
        return pass;
    }
    
    @Override
    public Boolean validateForDelete(Object arg0)
        throws BusinessException
    {
        return true;
    }
    
    @Override
    public Boolean validateForInsert(Object arg0)
        throws BusinessException
    {
        ActivityDTO activ = (ActivityDTO)arg0;
        // 验证唯一性
        if (!StringUtils.isEmpty(activ.getFlag()))
        {
            if (!("INFO1".equals(activ.getFlag())))
            {
                String flag = activ.getFlag();
                HashMap hm = new HashMap();
                hm.put("flag", flag);
                if (!"INFO6".equals(flag) && !"INFO7".equals(flag))
                {
                    hm.put("area", activ.getArea());
                }
                
                List<ActivityDTO> act = activityReadMapper.selectByFlag(hm);
                if (act.size() > 0)
                {
                    return Boolean.valueOf(false);
                    
                }
            }
        }
        return Boolean.valueOf(true);
    }
    
    @Override
    public Boolean validateForUpdate(Object arg0)
        throws BusinessException
    {
        Boolean pass = false;
        pass = this.validate(arg0);
        return pass;
    }
    
    // 通过orderDTO创建order
    public void setActivityByActivityDTO(Activity activity, ActivityDTO activityDTO)
    {
        if (!StringUtils.isEmpty(activityDTO.getSerial()))
        {
            activity.setSerial(activityDTO.getSerial());
        }
        if (!StringUtils.isEmpty(activityDTO.getProId()))
        {
            activity.setProId(activityDTO.getProId());
        }
        if (!StringUtils.isEmpty(activityDTO.getImage()))
        {
            activity.setImage(activityDTO.getImage());
        }
        if (!StringUtils.isEmpty(activityDTO.getFlag()))
        {
            activity.setFlag(activityDTO.getFlag());
        }
        if (null != activityDTO.getArea())
        {
            activity.setArea(activityDTO.getArea());
        }
        if (!StringUtils.isEmpty(activityDTO.getCreatedDtm()))
        {
            activity.setCreatedDtm(activityDTO.getCreatedDtm());
        }
        if (!StringUtils.isEmpty(activityDTO.getCreatedBy()))
        {
            activity.setCreatedBy(activityDTO.getCreatedBy());
        }
        if (!StringUtils.isEmpty(activityDTO.getLastModifiedDtm()))
        {
            activity.setLastModifiedDtm(activityDTO.getLastModifiedDtm());
        }
        if (!StringUtils.isEmpty(activityDTO.getLastModifiedBy()))
        {
            activity.setLastModifiedBy(activityDTO.getLastModifiedBy());
        }
        if (!StringUtils.isEmpty(activityDTO.getVersion()))
        {
            activity.setVersion(activityDTO.getVersion());
        }
        if (!StringUtils.isEmpty(activityDTO.getDeleted()))
        {
            activity.setDeleted(activityDTO.getDeleted());
        }
    }
    
    @Override
    public int insert(Object arg0)
        throws BusinessException
    {
        // TODO Auto-generated method stub
        return 0;
    }
    
    @Override
    public void editActivity(ActivityDTO activityDTO)
        throws BusinessException
    {
        Activity activity = activityReadMapper.selectByPrimaryKey(activityDTO.getId());
        setActivityByActivityDTO(activity, activityDTO);
        activity.setDescription(activityDTO.getDescription());
        activity.setTitle(activityDTO.getTitle());
        activity.setLastModifiedBy(activityDTO.getUserId());
        activity.setLastModifiedDtm(new Date());
        activityWriteMapper.updateByPrimaryKeySelective(activity);
    }
    
    @Override
    public void deleteActivity(Integer id)
        throws BusinessException
    {
        Activity activity = activityReadMapper.selectByPrimaryKey(id);
        Boolean pass = this.validateForDelete(activity);
        if (pass)
        {
            activity.setCreatedBy(SecurityUtils.getCurrentLogin().getUserId());
            activity.setCreatedDtm(new Date());
            activity.setLastModifiedBy(SecurityUtils.getCurrentLogin().getUserId());
            activity.setLastModifiedDtm(new Date());
            activityWriteMapper.deleteByPrimaryKey(activity);
        }
    }
    
    @Override
    public String getValueByCode(String code)
        throws BusinessException
    {
        return activityReadMapper.getValueByCode(code);
    }
    
    // 当图片资源被删除时将对应的图片image字段修改成空。
    @Override
    public void setNullById(String imageId)
        throws BusinessException
    {
        List<ActivityDTO> act = activityReadMapper.selectByImage(imageId);
        if (act.size() > 0)
        {
            for (int i = 0; i < act.size(); i++)
            {
                ActivityDTO ac = (ActivityDTO)act.get(i);
                String imaStr = ac.getImage();
                String[] imSp = imaStr.split(",");
                String result = "";
                // 当广告的image大于一个
                if (imSp.length > 1)
                {
                    // 删除的资源id和广告的image一致则删除（置成空）
                    for (int j = 0; j < imSp.length; j++)
                    {
                        if (imSp[j].toString().equals(imageId))
                        {
                            continue;
                        }
                        result = result + imSp[j].toString() + ",";
                    }
                    result = result.substring(0, result.length() - 1);
                    updateImage(ac.getId(), result);
                    // 当广告的image等于一个
                }
                else if (imSp.length == 1)
                {
                    // 删除的资源id和广告的image一致则删除（置成空）
                    if (imSp[0].toString().equals(imageId))
                    {
                        updateImage(ac.getId(), "");
                    }
                    // 当广告的image为空时不处理。
                }
                else
                {
                    continue;
                }
            }
        }
        
    }
    
    /**
     * 修改image字段
     */
    public void updateImage(Integer id, String image)
    {
        Activity activity = new Activity();
        activity.setId(id);
        activity.setImage(image);
        activityWriteMapper.updateByPrimaryKeySelective(activity);
    }
    
    public Boolean validateForInsertActivityList(ActivityList activityList)
    {
        Boolean pass = false;
        try
        {
            pass = this.validate(activityList);
        }
        catch (BusinessException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return pass;
    }
    
    @Override
    public int insertActivityList(ActivityList activityList)
    {
        Integer id = -1;
        Boolean pass = this.validateForInsertActivityList(activityList);
        if (pass)
        {
            activityList.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListWriteMapper.insertSelective(activityList);
            id = activityList.getId();
        }
        return id;
    }
    
    public Boolean validateForInsertActivityList(ActivityListDetail activityListDetail)
    {
        Boolean pass = false;
        try
        {
            pass = this.validate(activityListDetail);
        }
        catch (BusinessException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return pass;
    }
    
    @Override
    public int insertActivityListDetail(ActivityListDetail activityListDetail)
    {
        Integer activityListId = activityListDetail.getActivityListId();
        Integer id = 0;
        ActivityListDetail activityListDetail1 =  activityListDetailReadMapper.selectByActivityListId(activityListId);
        if (activityListDetail1 == null)
        {
            activityListDetail.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListDetailWriteMapper.insertSelective(activityListDetail);   
            id = activityListDetail.getId();
        }
        else{
            activityListDetail.setId(activityListDetail1.getId());
            activityListDetailWriteMapper.updateByPrimaryKeySelective(activityListDetail);
            id = activityListDetail1.getId();
        }
  
        return id;
    }
    
    public Boolean validateForInsertActivityList(ActivityListDetailDynamic activityListDetailDynamic)
    {
        Boolean pass = false;
        try
        {
            pass = this.validate(activityListDetailDynamic);
        }
        catch (BusinessException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return pass;
    }
    
    /**
     * 
     * [描述]：活动详情-动态-新增</br>
     *
     * @param activityListDetailDynamic
     * @return
     *
     */
    @Override
    public void insertActivityListDetailDynamic(List<ActivityDynamicReq> activityListDetailDynamics)
    {
        if (null == activityListDetailDynamics)
        {
            return;
        }
        
        for (ActivityDynamicReq createReq : activityListDetailDynamics)
        {
            ActivityListDetailDynamic activityListDetailDynamic = new ActivityListDetailDynamic();
            activityListDetailDynamic.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            
            // 对projectId
            List<DynamicProjectInfo> ProjectInfoList = createReq.getProjectInfoList();
            
            if (CollectionUtils.isNotEmpty(ProjectInfoList))
            {
                JsonArray jsonArray = new JsonArray();
                JsonObject proInfoJson = null;
                for (DynamicProjectInfo projectInfo : ProjectInfoList)
                {
                    proInfoJson = new JsonObject();
                    proInfoJson.addProperty("projectId", projectInfo.getProjectId());
                    proInfoJson.addProperty("url", projectInfo.getUrl());
                    
                    jsonArray.add(proInfoJson);
                }
                
                activityListDetailDynamic.setProjectInfo(jsonArray.toString());
                activityListDetailDynamic.setActivityDetailId(createReq.getActivityDetailId());
                activityListDetailDynamic.setType(createReq.getType());
            }
            
            activityListDetailDynamicWriteMapper.insertSelective(activityListDetailDynamic);
            Integer id = activityListDetailDynamic.getId();
            
            createReq.setId(id);
        }
    }
    
    @Override
    public List<ActivityList> queryActivityList(Integer id)
    {
        List<ActivityList> activityLists = activityListReadMapper.selectByActivityId(id);
        return activityLists;
    }
    
    @Override
    public ActivityListDetail queryActivityListDetail(Integer id)
    {
        ActivityListDetail activityListDetail = activityListDetailReadMapper.selectByActivityListId(id);
        return activityListDetail;
    }
    
    @Override
    public ActivityListDetailDTO queryActivityListDetailDTO(Integer id)
        throws BusinessException, LandseaException
    {
        ActivityList activityList = activityListReadMapper.selectByPrimaryKey(id);
        Activity activity = activityReadMapper.selectByPrimaryKey(activityList.getActivityId());
        ActivityListDetail activityListDetail = activityListDetailReadMapper.selectByActivityListId(id);
        ActivityListDetailDTO dto = new ActivityListDetailDTO();
        if (activityListDetail == null)
        {
            return dto = null;
        }
        else
        {
            dto.setActivityListId(id);
            dto.setId(activityListDetail.getId());
            dto.setActivityType(activityListDetail.getActivityType());
            dto.setBottomColor(activityListDetail.getBottomColor());
            dto.setCreatedDtm(activityListDetail.getCreatedDtm());
            dto.setDescription(activityListDetail.getDescription());
            dto.setDescriptionLocation(activityListDetail.getDescriptionLocation());
            dto.setMiddleText(activityListDetail.getMiddleText());
            dto.setTitle(activityListDetail.getTitle());
            dto.setType(activityListDetail.getType());
            dto.setName(activityListDetail.getName());
            dto.setImage(activityListDetail.getImage());
            dto.setHeadPicture(activityListDetail.getHeadPicture());
            dto.setMiddlePicture(activityListDetail.getMiddlePicture());
            FileDTO DTO = FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityListDetail.getImage()));
            FileDTO DTO1 =
                FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityListDetail.getMiddlePicture()));
            FileDTO DTO2 =
                FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityListDetail.getHeadPicture()));
            dto.setMiddlePicturePath(DTO1.getFullPath());
            dto.setImagePath(DTO.getFullPath());
            dto.setHeadPicturePath(DTO2.getFullPath());
            dto.setFlag(activity.getFlag());
            
            // 如果是动态，查询动态
            if ("3".equals(activityListDetail.getType()))
            {
                List<ActivityListDetailDynamicDTO> dynamicDtoList =
                    queryActivityListDetailDynamicDTO(activityListDetail.getId());
                dto.setActivityListDetailDynamic(dynamicDtoList);
            }
            
            return dto;
        }
        
    }
    
    @Override
    public List<ActivityListDetailDynamic> queryActivityListDetailDynamic(Integer id)
    {
        List<ActivityListDetailDynamic> activityListDetailDynamics =
            activityListDetailDynamicReadMapper.selectByActivityDetailId(id);
        return activityListDetailDynamics;
    }
    
    @Override
    public List<ActivityListDetailDynamicDTO> queryActivityListDetailDynamicDTO(Integer id)
        throws BusinessException, LandseaException
    {
        List<ActivityListDetailDynamicDTO> activityListDetailDynamicDTOs =
            new ArrayList<ActivityListDetailDynamicDTO>();
        List<ActivityListDetailDynamic> activityListDetailDynamics =
            activityListDetailDynamicReadMapper.selectByActivityDetailId(id);
        
        if (null == activityListDetailDynamics)
        {
            return activityListDetailDynamicDTOs;
        }
        
        for (ActivityListDetailDynamic activityListDetailDynamic : activityListDetailDynamics)
        {
            ActivityListDetailDynamicDTO dto = new ActivityListDetailDynamicDTO();
            
            dto.setId(activityListDetailDynamic.getId());
            dto.setType(activityListDetailDynamic.getType());
            
            String projectInfoJsonStr = activityListDetailDynamic.getProjectInfo();
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(projectInfoJsonStr))
            {
                List<DynamicProjectInfo> projectInfoList =
                    JsonObjectUtils.jsonStr2ListBean(projectInfoJsonStr, DynamicProjectInfo.class);
                
                List<ProjectDTO1> projectDTOList = new ArrayList<ProjectDTO1>();
                for (DynamicProjectInfo dynamicProjectInfo : projectInfoList)
                {
                    ProjectDTO1 projectDTO1 = new ProjectDTO1();
                    Project project = projectReadMapper.selectExistsById(dynamicProjectInfo.getProjectId());
                    projectDTO1.setProject(project);
                    projectDTO1.setUrl(dynamicProjectInfo.getUrl());
                    FileDTO DTO2 =
                        FileConverter.fromFileToDTO((SystemFile)this.fileService.get(project.getCoverImage()));
                    projectDTO1.setCoverImagePath(DTO2.getFullPath());
                    
                    projectDTOList.add(projectDTO1);
                }
                dto.setProjectList(projectDTOList);
            }
            activityListDetailDynamicDTOs.add(dto);
        }
        return activityListDetailDynamicDTOs;
    }
    
    @Override
    public void deleteActivityList(Integer id)
        throws BusinessException
    {
        List<ActivityList> activityLists = queryActivityList(id);
        for (ActivityList activityList : activityLists)
        {
            Boolean pass = this.validateForDelete(activityList);
            if (pass)
            {
                activityList.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
                activityListWriteMapper.deleteByPrimaryKey(activityList);
            }
            
        }
    }
    
    @Override
    public void deleteActivityListDetail(Integer id)
        throws BusinessException
    {
        ActivityListDetail activityListDetail = queryActivityListDetail(id);
        Boolean pass = this.validateForDelete(activityListDetail);
        if (pass)
        {
            activityListDetail.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListDetailWriteMapper.deleteByPrimaryKey(activityListDetail);
        }
    }
    
    @Override
    public void deleteActivityListDetailDynamic(Integer id)
        throws BusinessException
    {
        List<ActivityListDetailDynamic> activityListDetailDynamics = queryActivityListDetailDynamic(id);
        for (ActivityListDetailDynamic activityListDetailDynamic : activityListDetailDynamics)
        {
            Boolean pass = this.validateForDelete(activityListDetailDynamic);
            if (pass)
            {
                activityListDetailDynamic.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
                activityListDetailDynamicWriteMapper.deleteByPrimaryKey(activityListDetailDynamic);
            }
        }
    }
    
    @Override
    public void deleteActivityListDetailByPrimaryKey(Integer id)
        throws BusinessException
    {
        ActivityListDetail activityListDetail = activityListDetailReadMapper.selectByPrimaryKey(id);
        Boolean pass = this.validateForDelete(activityListDetail);
        if (pass)
        {
            activityListDetail.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListDetailWriteMapper.deleteByPrimaryKey(activityListDetail);
        }
    }
    
    @Override
    public void deleteActivityListByDetailId(Integer id)
        throws BusinessException
    {
        ActivityList activityList = activityListReadMapper.selectByPrimaryKey(id);
        Boolean pass = this.validateForDelete(activityList);
        if (pass)
        {
            activityList.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListWriteMapper.deleteByPrimaryKey(activityList);
        }
        
    }
    
    @Override
    public void deleteActivityListDetailDynamicByPrimaryKey(Integer id)
        throws BusinessException
    {
        ActivityListDetailDynamic activityListDetailDynamic =
            activityListDetailDynamicReadMapper.selectByPrimaryKey(id);
        Boolean pass = this.validateForDelete(activityListDetailDynamic);
        if (pass)
        {
            activityListDetailDynamic.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListDetailDynamicWriteMapper.deleteByPrimaryKey(activityListDetailDynamic);
        }
        
    }
    
    @Override
    public List<ActivityListDTO> queryList()
        throws BusinessException
    {
        List<ActivityListDTO> dtos = new ArrayList<ActivityListDTO>();
        // 查询品牌活动
        String flag1 = "INFO3";
        String flag2 = "INFO4";
        Activity activity1 = activityReadMapper.selectActivity3(flag1);
        Activity activity2 = activityReadMapper.selectActivity3(flag2);
        
        List<ActivityListDTO1> dto1s = new ArrayList<ActivityListDTO1>();
        ActivityListDTO activityListDTO1 = new ActivityListDTO();
        if (activity1 != null)
        {
            List<ActivityList> activityLists1 = activityListReadMapper.selectByActivityId(activity1.getId());
            
            activityListDTO1.setId(activity1.getId());
            activityListDTO1.setFlag(activity1.getFlag());
            activityListDTO1.setPublished(activity1.getPublished());
            activityListDTO1.setDescription(activity1.getDescription());
            activityListDTO1.setTitle(activity1.getTitle());
            activityListDTO1.setImage(activity1.getImage());
            
            for (ActivityList activityList : activityLists1)
            {
                ActivityListDTO1 dto1 = new ActivityListDTO1();
                dto1.setActivityId(activityList.getActivityId());
                dto1.setDescription(activityList.getDescription());
                dto1.setId(activityList.getId());
                dto1.setName(activityList.getName());
                dto1.setShowInPhone(activityList.getShowInPhone());
                dto1.setUrl(activityList.getUrl());
                dto1.setCreatedDtm(activityList.getCreatedDtm());
                FileDTO pcDTO =
                    FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityList.getPcImage()));
                dto1.setPcImagePath(pcDTO.getFullPath());
                FileDTO wechatDTO =
                    FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityList.getWechatImage()));
                dto1.setWechatImagePath(wechatDTO.getFullPath());
                dto1.setPcImage(activityList.getPcImage());
                dto1.setWechatImage(activityList.getWechatImage());
                dto1s.add(dto1);
            }
            activityListDTO1.setActivityListDTO1s(dto1s);
            
            dtos.add(activityListDTO1);
        }
        
        if (activity2 != null)
        {
            List<ActivityList> activityLists2 = activityListReadMapper.selectByActivityId(activity2.getId());
            
            ActivityListDTO activityListDTO2 = new ActivityListDTO();
            activityListDTO2.setId(activity2.getId());
            activityListDTO2.setFlag(activity2.getFlag());
            activityListDTO2.setPublished(activity2.getPublished());
            activityListDTO2.setDescription(activity2.getDescription());
            activityListDTO2.setTitle(activity2.getTitle());
            activityListDTO2.setImage(activity2.getImage());
            List<ActivityListDTO1> dto2s = new ArrayList<>();
            for (ActivityList activityList : activityLists2)
            {
                ActivityListDTO1 dto2 = new ActivityListDTO1();
                dto2.setActivityId(activityList.getActivityId());
                dto2.setDescription(activityList.getDescription());
                dto2.setId(activityList.getId());
                dto2.setName(activityList.getName());
                dto2.setShowInPhone(activityList.getShowInPhone());
                dto2.setUrl(activityList.getUrl());
                dto2.setOrder(activityList.getOrder());
                dto2.setCreatedDtm(activityList.getCreatedDtm());
                FileDTO pcDTO =
                    FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityList.getPcImage()));
                dto2.setPcImagePath(pcDTO.getFullPath());
                FileDTO wechatDTO =
                    FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityList.getWechatImage()));
                dto2.setWechatImagePath(wechatDTO.getFullPath());
                dto2.setPcImage(activityList.getPcImage());
                dto2.setWechatImage(activityList.getWechatImage());
                dto2s.add(dto2);
            }
            activityListDTO2.setActivityListDTO1s(dto2s);
            
            dtos.add(activityListDTO2);
        }
       
        return dtos;
    }
    
    @Override
    public void editActivityList(List<ActivityList> activityList)
        throws BusinessException
    {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        for (ActivityList activityList2 : activityList)
        {
            activityList2.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            
            paramMap.put("activityId", activityList2.getActivityId());
            paramMap.put("order", activityList2.getOrder());
            ActivityList activityListDb = activityListReadMapper.selectByAcIdAndOrder(paramMap);
            if (null == activityListDb)
            {
                // 新增
                int id = activityListWriteMapper.insertSelective(activityList2);
                activityList2.setId(id);
            }
            else
            {
                
                activityListWriteMapper.updateByacIdAndOrder(activityList2);
            }
        }
    }
    
    @Override
    public void editActivityListDetail(ActivityListDetail activityListDetail)
        throws BusinessException
    {
        Boolean pass = this.validateForUpdate(activityListDetail);
        if (pass)
        {
            activityListDetail.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListDetailWriteMapper.updateByPrimaryKeySelective(activityListDetail);
        }
    }
    
    @Override
    public void editActivityListDetailDynamic(ActivityListDetailDynamic activityListDetailDynamic)
        throws BusinessException
    {
        Boolean pass = this.validateForUpdate(activityListDetailDynamic);
        if (pass)
        {
            activityListDetailDynamic.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListDetailDynamicWriteMapper.updateByPrimaryKeySelective(activityListDetailDynamic);
        }
    }
    
    @Override
    public void canclePublishedActivity(Integer id)
    {
        activityWriteMapper.updateCanclePublished(id);
        
    }
    
    @Override
    public Integer publishedActivity(Map pmap)
        throws BusinessException
    {
        Integer id = Integer.parseInt(pmap.get("id").toString());
        List<ActivityListDetail> activityDetailLists = activityListDetailReadMapper.selectByActivityId(id);
        
        if (null == activityDetailLists)
        {
            activityDetailLists = new ArrayList<ActivityListDetail>();
        }
        
        Integer a = 0;
        String flag = pmap.get("flag").toString();
        if ("INFO4".equals(flag))
        {
            Activity activity = activityReadMapper.selectByFlagAndPublished(flag);
            if (activity == null)
            {
                if (activityDetailLists.size() == 5)
                {
                    a = activityWriteMapper.updatePublished(id);
                }
                else
                {
                    a = -100;
                }
            }
            else
            {
                a = -200;
            }
        }
        else if ("INFO3".equals(flag))
        {
            Activity activity = activityReadMapper.selectByFlagAndPublished(flag);
            if (activity == null)
            {
                if (activityDetailLists.size() >= 1)
                {
                    a = activityWriteMapper.updatePublished(id);
                }
                else
                {
                    a = -100;
                }
            }
            else
            {
                a = -200;
            }
        }
        return a;
    }
    
    @Override
    public List<ActivityListDTO1> queryActivityListDTO(Integer id)
        throws BusinessException
    {
        List<ActivityListDTO1> activityListDTO1s = new ArrayList<ActivityListDTO1>();
        Activity activity = activityReadMapper.selectByPrimaryKey(id);
        if("INFO3".equals(activity.getFlag())){
            List<ActivityList> activityLists = activityListReadMapper.selectByActivityId(id);
            for (ActivityList activityList : activityLists)
            {
                ActivityListDTO1 activityListDTO1 = new ActivityListDTO1();
                activityListDTO1.setId(activityList.getId());
                activityListDTO1.setActivityId(activityList.getActivityId());
                activityListDTO1.setCreatedDtm(activityList.getCreatedDtm());
                activityListDTO1.setDescription(activityList.getDescription());
                activityListDTO1.setName(activityList.getName());
                activityListDTO1.setShowInPhone(activityList.getShowInPhone());
                activityListDTO1.setUrl(activityList.getUrl());
                activityListDTO1.setPcImage(activityList.getPcImage());
                activityListDTO1.setWechatImage(activityList.getWechatImage());
                activityListDTO1.setOrder(activityList.getOrder());
                FileDTO wechatDTO =
                    FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityList.getWechatImage()));
                activityListDTO1.setWechatImagePath(wechatDTO.getFullPath());
                FileDTO pcDTO = FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityList.getPcImage()));
                activityListDTO1.setPcImagePath(pcDTO.getFullPath());
                activityListDTO1.setFlag(activity.getFlag());
                activityListDTO1s.add(activityListDTO1);
            }
        }else if ("INFO4".equals(activity.getFlag()))
        {
            List<ActivityList> activityLists = activityListReadMapper.selectByActivityId(id);
            for (ActivityList activityList : activityLists)
            {
                ActivityListDTO1 activityListDTO1 = new ActivityListDTO1();
                activityListDTO1.setId(activityList.getId());
                activityListDTO1.setActivityId(activityList.getActivityId());
                activityListDTO1.setCreatedDtm(activityList.getCreatedDtm());
                ActivityListDetail detail = activityListDetailReadMapper.selectByActivityListId(activityList.getId());
                if (null != detail)
                {
                    activityListDTO1.setDescription(detail.getDescription());
                }
                activityListDTO1.setName(activityList.getName());
                activityListDTO1.setShowInPhone(activityList.getShowInPhone());
                activityListDTO1.setUrl(activityList.getUrl());
                activityListDTO1.setPcImage(activityList.getPcImage());
                activityListDTO1.setWechatImage(activityList.getWechatImage());
                activityListDTO1.setOrder(activityList.getOrder());
                FileDTO wechatDTO =
                    FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityList.getWechatImage()));
                activityListDTO1.setWechatImagePath(wechatDTO.getFullPath());
                FileDTO pcDTO = FileConverter.fromFileToDTO((SystemFile)this.fileService.get(activityList.getPcImage()));
                activityListDTO1.setPcImagePath(pcDTO.getFullPath());
                activityListDTO1.setFlag(activity.getFlag());
                activityListDTO1s.add(activityListDTO1);
            }
        }
        
        
        return activityListDTO1s;
    }
    
    @Override
    public void editActivityAndActivityListDTO(ActivityAndActivityListDTO dto)
    {
        // 处理ActivityList
        List<ActivityList> activityLists = dto.getActivityLists();
        
        // 查询数据库中activity对应的列表集合
        List<ActivityList> activityListsDataBase = activityListReadMapper.selectByActivityId(dto.getId());
        
        // 構造要新增的
        List<ActivityList> insertList = new ArrayList<ActivityList>();
        // 構造要修改的
        List<ActivityList> updateList = new ArrayList<ActivityList>();
        // 構造要delete
        List<ActivityList> deleteList = new ArrayList<ActivityList>();
        
        for (ActivityList activityList : activityLists)
        {
            Integer id = activityList.getId();
            if (null == id)
            {
                insertList.add(activityList);
            }
            
            // 看是不是要修改的
            boolean isExists = isContains(activityList, activityListsDataBase);
            if (isExists)
            {
                updateList.add(activityList);
            }
            else
            {
                // 数据为非法数据，记录日志后丢弃
                LOG.error("editActivityAndActivityListDTO|非法的activityList|ID=" + id);
            }
        }
        
        // 判断哪些是需要删除的
        if (CollectionUtils.isNotEmpty(activityListsDataBase))
        {
            for (ActivityList ac : activityListsDataBase)
            {
                // 如果不在更新列表里面，那肯定是要删除
                boolean isExists = isContains(ac, updateList);
                if (!isExists)
                {
                    deleteList.add(ac);
                }
            }
        }
        
        // .......
        for (ActivityList activityList : deleteList)
        {
            activityListWriteMapper.deleteByPrimaryKeyPhysical(activityList.getId());
            ActivityListDetail activityListDetail =
                activityListDetailReadMapper.selectByActivityListId(activityList.getId());
            if (activityListDetail != null)
            {
                activityListDetailDynamicWriteMapper.deleteByActivityListId(activityListDetail.getId());
            }
            
            activityListDetailWriteMapper.deleteByActivityListId(activityList.getId());
            
        }
        
        for (ActivityList activityList : insertList)
        {
            // 新增ActivityList
            activityList.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListWriteMapper.insertSelective(activityList);
            Integer id = activityList.getId();
            activityList.setId(id);
        }
        
        for (ActivityList activityList : updateList)
        {
            activityList.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListWriteMapper.updateByPrimaryKeySelective(activityList);
        }
    }
    
    /**
     * 
     * [简要描述]：判断activityList是否在list中</br>
     * [详细描述]：根据ID判断</br>
     * [作者]：Crystal(2017-08-24)</br>
     *
     * @param activityList
     * @param list
     * @return
     *
     */
    public boolean isContains(ActivityList activityList, List<ActivityList> list)
    {
        if (null == activityList || CollectionUtils.isEmpty(list))
        {
            return false;
        }
        
        for (ActivityList ac : list)
        {
            Integer idInt = activityList.getId();
            if (null != idInt && activityList.getId().intValue() == ac.getId().intValue())
            {
                return true;
            }
        }
        
        return false;
    }
    
    @Override
    public void saveDynamicAcInfoInsert(SaveActivityListDetailDynamicReq saveActivityListDetailDynamicReq)
    {
        Integer activityListId = saveActivityListDetailDynamicReq.getActivityListId();
        ActivityListDetail activityListDetail = activityListDetailReadMapper.selectByActivityListId(activityListId);
        if (activityListDetail == null)
        {
            saveActivityListDetailDynamicReq.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            activityListDetailWriteMapper.insertSelective(saveActivityListDetailDynamicReq);
        }
        else{
            saveActivityListDetailDynamicReq.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            saveActivityListDetailDynamicReq.setId(activityListDetail.getId());
            activityListDetailWriteMapper.updateByPrimaryKeySelective(saveActivityListDetailDynamicReq);
        }
        List<ActivityDynamicReq> dynamicReqList = saveActivityListDetailDynamicReq.getDynamicsList();
        
        if (CollectionUtils.isEmpty(dynamicReqList))
        {
            return;
        }
        
        Integer detailId = saveActivityListDetailDynamicReq.getId();
        
        for (ActivityDynamicReq adr : dynamicReqList)
        {
            adr.setActivityDetailId(detailId);
        }
        
        // 新增动态
        insertActivityListDetailDynamic(saveActivityListDetailDynamicReq.getDynamicsList());
    }
    
    @Override
    public void saveDynamicAcInfoEdit(SaveActivityListDetailDynamicReq saveActivityListDetailDynamicReq)
    {
        saveActivityListDetailDynamicReq.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
        activityListDetailWriteMapper.updateByPrimaryKeySelective(saveActivityListDetailDynamicReq);
        List<ActivityDynamicReq> dynamicReqList = saveActivityListDetailDynamicReq.getDynamicsList();
        
        if (CollectionUtils.isEmpty(dynamicReqList))
        {
            return;
        }
        
        Integer detailId = saveActivityListDetailDynamicReq.getId();
        
        for (ActivityDynamicReq adr : dynamicReqList)
        {
            adr.setActivityDetailId(detailId);
            adr.setId(null);
        }
        
        // 先删除
        activityListDetailDynamicWriteMapper.deleteByActivityListId(detailId);
        
        // 更新
        updateActivityListDetailDynamic(saveActivityListDetailDynamicReq.getDynamicsList());
    }
    
    /**
     * 
     * [描述]：活动详情-动态-修改</br>
     *
     * @param activityListDetailDynamic
     * @return
     *
     */
    @Override
    public void updateActivityListDetailDynamic(List<ActivityDynamicReq> activityListDetailDynamics)
    {
        if (null == activityListDetailDynamics)
        {
            return;
        }
        
        for (ActivityDynamicReq createReq : activityListDetailDynamics)
        {
            ActivityListDetailDynamic activityListDetailDynamic = new ActivityListDetailDynamic();
            activityListDetailDynamic.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            
            // 对projectId
            List<DynamicProjectInfo> ProjectInfoList = createReq.getProjectInfoList();
            
            if (CollectionUtils.isNotEmpty(ProjectInfoList))
            {
                JsonArray jsonArray = new JsonArray();
                JsonObject proInfoJson = null;
                for (DynamicProjectInfo projectInfo : ProjectInfoList)
                {
                    proInfoJson = new JsonObject();
                    proInfoJson.addProperty("projectId", projectInfo.getProjectId());
                    proInfoJson.addProperty("url", projectInfo.getUrl());
                    
                    jsonArray.add(proInfoJson);
                }
                
                activityListDetailDynamic.setProjectInfo(jsonArray.toString());
                activityListDetailDynamic.setActivityDetailId(createReq.getActivityDetailId());
                activityListDetailDynamic.setType(createReq.getType());
                activityListDetailDynamic.setId(createReq.getId());
            }
            
            if (null != createReq.getId())
            {
                activityListDetailDynamicWriteMapper.updateByPrimaryKeySelective(activityListDetailDynamic);
            }
            else
            {
                activityListDetailDynamicWriteMapper.insertSelective(activityListDetailDynamic);
            }
        }
    }
}
